package com.momoc.multi.chat.room.core.consumer;

import com.momoc.multi.chat.room.common.config.MachineConfig;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author momoc
 * @version 1.0
 * @className RabbitMessageConfig
 * @description
 * @date 2024/5/28 11:01
 */
@RequiredArgsConstructor
@Getter
@Configuration
public class RabbitMessageConfig implements InitializingBean {


    public static String INSTANCE_EXCHANGE_NAME_PREFIX = "aurora.momoc.exchange.machine.%s";

    String instanceQueueName;
    String instanceExchangeName;



    /**
     * json序列化
     * @return
     */

    @Bean
    public MessageConverter jackjsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(instanceExchangeName);
    }

    /**
     * 声明发送消息的队列
     * @return
     */
    @Bean
    public Queue sendMessageToCurrenInstanceUserQueue(){
        QueueBuilder durable = QueueBuilder.durable(instanceQueueName);
        return durable.build();
    }

    @Bean
    public Binding fanoutBindingQueue(){
        return BindingBuilder.bind(sendMessageToCurrenInstanceUserQueue()).to(fanoutExchange());
    }


    @Bean
    RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry(){
        return new RabbitListenerEndpointRegistry();
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        instanceQueueName  = "aurora.momoc.queue.machine." + MachineConfig.getMachineId();
        instanceExchangeName = String.format(INSTANCE_EXCHANGE_NAME_PREFIX, MachineConfig.getMachineId());
    }
}
